import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

class Student{
    //私有属性name
    private String name = "bit";
    //公有属性age
    public int age = 18; //不带参数的构造方法

    public Student(){
        System.out.println("Student()");
    }

    private Student(String name,int age) {
        this.name = name;
        this.age = age;
        System.out.println("Student(String,name)");
    }

    private void eat(){
        System.out.println("i am eat");
    }

    public void sleep(){
        System.out.println("i am pig");
    }

    private void function(String str) {
        System.out.println(str);
    }

    @Override
    public String toString() {
        return "Student{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}

public class TestDemo {
    public static void reflectNewInstance() {
        //获取对象
        Class<?> c3 = null;
        try {
            c3 = Class.forName("TestDemo.Student");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        try {
            Student student = (Student)c3.newInstance();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }
        //获取构造
        Constructor<?> constructor = null;
        try {
            constructor = c3.getDeclaredConstructor(String.class,int.class);
        } catch (NoSuchMethodException ex) {
            ex.printStackTrace();
        }
        constructor.setAccessible(true);

    }

    public static void main(String[] args) {
        Student student = new Student();
        reflectNewInstance();
        System.out.println(student);


    }
    //反射对象的三种方式
    public static void main1(String[] args) {
        Student student = new Student();
        Class<?> c1 = student.getClass();
        try {
            Student student1 = (Student)c1.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        Class<?> c2 = Student.class;
        try {
            Student student2 = (Student)c2.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        try {
            Class<?> c3 = Class.forName("TestDemo.Student");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
